package com.jsgt.greekfire.common.util

import android.text.InputFilter
import android.text.TextUtils
import android.widget.EditText
import com.fhx.core.AppContext
import com.fhx.core.utils.SharePreferencesUtil
import com.google.gson.Gson
import com.jsgt.greekfire.WALLET_INFO_LIST
import com.jsgt.greekfire.dao.model.IdentityBean


object WalletManager {
    fun getLocalWallets(): HashSet<IdentityBean> {
        val setString = SharePreferencesUtil.getStringSet(AppContext.instance, WALLET_INFO_LIST)
        if (setString == null || setString.isEmpty()) {
            return HashSet<IdentityBean>()
        } else {
            val setBean = HashSet<IdentityBean>()
            val gson = Gson()

            for (str in setString) {
                val bean = gson.fromJson(str, IdentityBean::class.java)
                setBean.add(bean)
            }
            return setBean
        }
    }

    private fun setBean2String(setBean: HashSet<IdentityBean>): HashSet<String> {
        val setString = HashSet<String>()
        for (bean in setBean) {
            val json = Gson().toJson(bean)
            setString.add(json)
        }
        return setString
    }

    fun addWallet(bean: IdentityBean) {
        val set = getLocalWallets()
        bean.priKey = AESOperator.getInstance().encryptJni(bean.priKey)
        if (set.isNotEmpty()) {
            for (wallet in set) {
                if (wallet.priKey == bean.priKey) {
                    if(!TextUtils.isEmpty(wallet.mnemonic)){
                        bean.mnemonic = AESOperator.getInstance().decryptJni(wallet.mnemonic)
                    }
                    set.remove(wallet)
                    break
                }
            }
        }
        if (!TextUtils.isEmpty(bean.mnemonic)) {
            bean.mnemonic = AESOperator.getInstance().encryptJni(bean.mnemonic)
        }
        set.add(bean)

        SharePreferencesUtil.saveStringSet(
            AppContext.instance,
            WALLET_INFO_LIST,
            setBean2String(set)
        )
    }


    /**
     * 禁止EditText输入空格和换行符
     *
     * @param editText EditText输入框
     */
    fun setEditTextInputSpace(editText: EditText) {
        val filter = InputFilter { source, start, end, dest, dstart, dend ->
            if (source == " " || source.toString().contentEquals("\n")) {
                ""
            } else {
                null
            }
        }
        editText.filters = arrayOf(filter)
    }
}